package de.unibielefeld.msp.zusatzstoffe;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import de.unibi.techfak.msp.eatThis.bean.FoodBean;
import de.unibielefeld.msp.zusatzstoffe.utility.Constants;
import de.unibielefeld.msp.zusatzstoffe.utility.ServiceConsumer;
import flexjson.JSONDeserializer;

/**
 * Der Startscreen.
 * 
 * @author Henry
 * 
 */
public class ZusatzstoffeActivity extends Activity {

    String ean;
    AlertDialog.Builder builder;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        builder = new AlertDialog.Builder(this);

        final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        ImageButton barcode = (ImageButton) findViewById(R.id.barcodeImage);
        ImageButton foodlist = (ImageButton) findViewById(R.id.listImage);

        barcode.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                // Only give access to Buttons if networking is enabled.
                if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
                        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
                        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
                    IntentIntegrator.initiateScan(ZusatzstoffeActivity.this);
                } else {
                    CharSequence text = "Keine Internetverbindung vorhanden!";
                    Toast toast = Toast.makeText(getApplicationContext(), text,
                            Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });

        foodlist.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
                        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING
                        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED) {
                    Intent intent = new Intent(view.getContext(),
                            Foodlist.class);
                    startActivity(intent);
                } else {
                    CharSequence text = "Keine Internetverbindung vorhanden!";
                    Toast toast = Toast.makeText(getApplicationContext(), text,
                            Toast.LENGTH_LONG);
                    toast.show();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        CharSequence text = "Fehler beim Scannen";

        IntentResult scanResult = IntentIntegrator.parseActivityResult(
                requestCode, resultCode, intent);
        if (scanResult != null) {
            text = scanResult.getContents();
            if (text == null) {
                text = "Fehler beim Scannen";
            } else {
                new FoodAsync().execute("ean", text.toString());
            }
        }
    }

    /**
     * Optionsmenü.
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menuOpenSettings:
                startActivity(new Intent(this, Settings.class));
                return true;
                
            case R.id.menuOpenInfos:
                builder.setTitle("Disclaimer");
                builder.setMessage(Constants.INFORMATION);
//                builder.setPositiveButton("Ja",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog,
//                                    int which) {
//                                Intent intent = new Intent(
//                                        getApplicationContext(),
//                                        NewFoodActivity.class);
//                                intent.putExtra(NewFoodActivity.EAN_KEY, ean);
//                                startActivity(intent);
//                                return;
//                            }
//                        });
//                builder.setNegativeButton("Nein",
//                        new DialogInterface.OnClickListener() {
//                            public void onClick(DialogInterface dialog,
//                                    int which) {
//                                return;
//                            }
//                        });
                final AlertDialog alert = builder.create();
                alert.show();
                return true;
                
        }
        return super.onOptionsItemSelected(item);
    }

    public class FoodAsync extends AsyncTask<String, Void, String> {

        private final ProgressDialog dialog = new ProgressDialog(
                ZusatzstoffeActivity.this);

        // can use UI thread here
        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Waiting for data ...");
            this.dialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            HttpResponse response;
            String responseString = null;
            ResponseHandler<String> responseHandler;
            HttpGet url;

            try {

                url = new HttpGet(Constants.CONNECTION_PREFIX + "?" + params[0]
                        + "=" + params[1]);

                responseHandler = new BasicResponseHandler();

                response = ServiceConsumer.execute(url);

                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    ean = params[1];

                    return null;

                }

                responseString = responseHandler.handleResponse(response);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(final String result) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }

            if (result == null) {

                builder.setTitle("Artikel nicht gefunden!");
                builder.setMessage("Soll das Produkt eingetragen werden?");
                builder.setPositiveButton("Ja",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent intent = new Intent(
                                        getApplicationContext(),
                                        NewFoodActivity.class);
                                intent.putExtra(NewFoodActivity.EAN_KEY, ean);
                                startActivity(intent);
                                return;
                            }
                        });
                builder.setNegativeButton("Nein",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                return;
                            }
                        });
                final AlertDialog alert = builder.create();
                alert.show();
                return;
            }

            FoodBean fb = new JSONDeserializer<FoodBean>().deserialize(result);
            Intent intent = new Intent(getApplicationContext(), FoodItem.class);
            intent.putExtra("NAME", fb.getName());
            intent.putExtra("FOODGROUP", fb.getName());
            intent.putExtra("INGREDIENTS", fb.getIngredients());
            intent.putExtra("EAN", fb.getEan());

            startActivity(intent);
        }

    }

}